import { ITestState } from './types'
import {createAsyncThunk, createSlice,PayloadAction} from '@reduxjs/toolkit'
// 1. 创建state 的model 声明，即ITestState

// 2. 定义状态初始值
const initnalState: ITestState = {
    name: "test",
    age: 10
}
// 3. 定义action,init 为生成的创建action函数 

export const init=createAsyncThunk<ITestState,{name:string,age:number}>('test/init',async ({name,age})=>{
    return {
        name,age
    }
})

// 4. 定义slice

const testSlice=createSlice({
    // 名称，
    name:'test',
    // 初始化状态
    initialState:initnalState,
    // reducer 
    reducers:{
        changeName:(state,action:PayloadAction<string>)=>{
            // 使用immer
            state.name=action.payload
        }
    },
    extraReducers:(builder)=>{
        builder.addCase(init.pending,(state)=>{
            state.name="pending"
        })
        builder.addCase(init.fulfilled,(state,action:PayloadAction<ITestState>)=>{
            state=action.payload
        })
        builder.addCase(init.rejected,(state)=>{
            state.name="rejected"
        })
    }
})
export const {changeName} =testSlice.actions
export const testReducer=testSlice.reducer